package com.banfeiguanli.springboot.service;

import com.banfeiguanli.springboot.common.Constant;
import com.banfeiguanli.springboot.common.Result;
import com.banfeiguanli.springboot.entity.ExpenseApply;
import com.banfeiguanli.springboot.entity.dto.ExpenseApplyDTO;
import com.banfeiguanli.springboot.mapper.ExpenseApplyMapper;
import com.banfeiguanli.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExpenseApplyService {
    @Autowired
    private ExpenseApplyMapper expenseApplyMapper;

    ////获取用户所在班级的申请记录
    public Result getApplyRecord(String token, Integer pageNumber, Integer pageSize, String searchUser, String searchReason) {
        Map<String, Object> data = new HashMap<>();
        //从token中提取userID
        Integer userID = TokenUtils.getIdByToken(token);
        //查询
        pageNumber = (pageNumber - 1) * pageSize;
        List<ExpenseApply> classApplyRecord = expenseApplyMapper.getApplyRecord(userID, pageNumber, pageSize, searchUser, searchReason);
        data.put("classApplyRecord", classApplyRecord);
        //统计总数用于分页
        Integer classApplyRecordTotal = expenseApplyMapper.countClassApplyRecordTotal(userID, searchUser, searchReason);
        data.put("classApplyRecordTotal", classApplyRecordTotal);
        return Result.success(data);
    }

    //申请班费
    public Result applyClassExpense(ExpenseApplyDTO expenseApplyDTO) {
        Map<String, Object> data = new HashMap<>();
        //从token获取userID
        Integer userID = TokenUtils.getIdByToken(expenseApplyDTO.getToken());
        expenseApplyDTO.setUserID(userID);
        //数据处理
        expenseApplyDTO.setApplyAmount(expenseApplyDTO.getApplyAmount() * (-1));
        //插入数据申请
        Integer changeRow = expenseApplyMapper.applyClassExpense(expenseApplyDTO);
        if (changeRow != 1) {
            return Result.error(Constant.CODE_660, "班费申请失败!");
        }
        return Result.success("申请成功！", data);
    }

    //撤销班费申请
    public Result cancelApply(Integer expApplyID) {
        Map<String, Object> data = new HashMap<>();
        Integer changeRow = expenseApplyMapper.cancelApply(expApplyID);
        if (changeRow != 1) {
            return Result.error(Constant.CODE_661, "撤销失败!");
        }
        data.put("changeRow", changeRow);
        return Result.success("撤销成功！", data);
    }
}
